﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace XFABManager
{

    /// <summary>
    /// 下载文件的请求
    /// </summary>
    public class DownloadFileRequest : CustomAsyncOperation<DownloadFileRequest>
    {

        /// <summary>
        /// 当前的下载速度 单位 字节
        /// </summary>
        public long CurrentSpeed {
            get; protected set;
        }
        /// <summary>
        /// 格式化之后的下载速度
        /// </summary>
        public string CurrentSpeedFormatStr { get; protected set; } = string.Empty;

        public string file_url {
            get;protected set;
        }

        protected DownloadTool downloadTool;

        public DownloadFileRequest() {
            downloadTool = new DownloadTool();
        }

        internal IEnumerator Download(string file_url, string localfile )
        {
            this.file_url = file_url;
            int retryCount = 0;
            do
            {
                retryCount++;
                if (!string.IsNullOrEmpty(downloadTool.error))
                {
                    yield return new WaitForSeconds(1);
                }

                downloadTool.Start(file_url, localfile);

                while (!downloadTool.isDone)
                {
                    yield return null;
                    progress = downloadTool.Progress;
                    CurrentSpeed = downloadTool.CurrentSpeed;
                    CurrentSpeedFormatStr = downloadTool.CurrentSpeedFormatStr;
                }

            } while (!string.IsNullOrEmpty(downloadTool.error) && retryCount <= 3);

            if (!string.IsNullOrEmpty(downloadTool.error))
            {
                error = string.Format("下载文件失败:{0} url:{1}", downloadTool.error,file_url);
            }

            Completed();
        }


        public static DownloadFileRequest DownloadFile(string file_url, string localfile)
        {
            string key = string.Format("DownloadFile:{0}", file_url);
            return AssetBundleManager.ExecuteOnlyOnceAtATime<DownloadFileRequest>(key, () => {
                DownloadFileRequest downloadFileRequest = new DownloadFileRequest();
                CoroutineStarter.Start(downloadFileRequest.Download(file_url, localfile));
                return downloadFileRequest;
            });
        }


    }

}

